//
//  ModalMenu.m
//  wechatManager
//
//  Created by tangchunhui on 15/3/29.
//  Copyright (c) 2015年 tangchunhui. All rights reserved.
//

#import "ModalMenu.h"
#import "Global.h"
#import "Menu.h"
#import "DataModal.h"
#import "DataBase.h"

@implementation ModalMenu

-(NSDictionary *)modalUrl{
    NSString *urlString =[NSString  stringWithFormat:@"%@/index.php/Home/Patient/getAccessToken?appid=%@",[Global host],[Global weixinhao]];
    NSURL *url1 = [NSURL URLWithString:urlString];
    NSError *error;
    NSData *data1 = [NSData dataWithContentsOfURL:url1 options:0  error:&error];
    NSDictionary *access = data1 ? [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
    NSString *accesstoken = [access valueForKey:@"access"];
    
    
    NSString  *url=[NSString  stringWithFormat:@"https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%@",accesstoken];
    
    NSDictionary *dic = @{@"url":url,
                          @"method":@"GET"
                          };
 
    return dic;
}


-(void)processSuccess:(NSDictionary *)results {
    //    NSDictionary *info = [results valueForKey:@"info"];
       NSLog(@"%@",results);
    NSDictionary *menus = [results objectForKey:@"menu"];
    NSArray *datas = [menus objectForKey:@"button"];
    [[DataModal instance]deleteEntity:@"Menu" whereString:@""];
    int menuid =1;
    for (NSDictionary *menuData in datas){
        Menu *menu = (Menu *)[[DataModal instance]createNewItem:@"Menu"];
        menu.menuid = [NSNumber numberWithInt:menuid];
        menu.type = [menuData valueForKey:@"type"];
        menu.key = [menuData valueForKey:@"key"];
        menu.name = [menuData valueForKey:@"name"];
        menu.url = [menuData valueForKey:@"url"];
        menu.parentid = 0;
        NSArray *submenus = [menuData valueForKey:@"sub_buttons"];
        int parentmenuid = menuid;
        for (NSDictionary *menuData1 in submenus){
            menuid ++;
            Menu *menu1 = (Menu *)[[DataModal instance]createNewItem:@"Menu"];
            menu1.menuid = [NSNumber numberWithInt:menuid];
            menu1.type = [menuData1 valueForKey:@"type"];
            menu1.key = [menuData1 valueForKey:@"key"];
            menu1.name = [menuData1 valueForKey:@"name"];
            menu1.url = [menuData1 valueForKey:@"url"];

            menu1.parentid = [NSNumber numberWithInt:parentmenuid];
        
        
        }
        menuid++;
        
    }
    NSError *error;
    [[DataModal instance].managedObjectContext save:&error];
    
    
}

@end
